from nicegui import ui,run,app
from config import database_path
from .comm import DATA
import shelve
from public import textfsm_run
import webview
import pandas as pd

class run_textfsms:
    def __init__(self,grid) -> None:
        self.grid=grid
    
        
    async def run_textfsms(self,tablesnames,button:ui.button):
        
        def get_tables_dict(datas):
            result={}
            for tablename in datas:
                result.update({tablename:datas['tablename']['result']})
            return result
            
        with shelve.open(database_path) as db:
            public_datas=db['public_datas']
            run_datas=db['run_datas']
            
            
        DATA_public_datas=DATA(public_datas,key='设备类型')
        DATA_run_datas=DATA(run_datas,key='表格名称')
        run_confs=[]
        for tablename  in tablesnames:
            run_data=DATA_run_datas.find(tablename)
            public_data=DATA_public_datas.find(run_data['设备类型'])
            run_confs.append(run_data.update(public_data))

        if run_confs:
            notification = ui.notification(message='开始任务配置解析!!!',position='top',color='blue',spinner=True,timeout=60*60*2)
            try:
                button.disable()
                self.data= await run.cpu_bound(textfsm_run.run_joblib,run_confs)
                # self.show_Analysis_results()
                with shelve.open(database_path) as db:
                    db['tables_dict']=get_tables_dict(self.data)
                        
                
            except:
                notification.message='任务失败!!!'
                notification.color="red"
                notification.spinner=False
                notification.close_button=True
            else:
                notification._props['options']['timeout']=5*1000
                notification.spinner =False
                notification.type='info'
                notification.message='任务完成!!!'
                notification.color="green"
                notification.close_button=True
            finally:
                button.enable()



    async def run_process_excel(self):
        pass


def layout():
    with shelve.open(database_path) as db:
        public_datas=db['public_datas']
        run_datas=db['run_datas']
        excel_task=db['excel_task']

    # print(excel_task)
    DATA_public_datas=DATA(public_datas,key='设备类型')
    DATA_run_datas=DATA(run_datas,key='表格名称')
    textfsms=ui.select(DATA_run_datas.find_keys(),multiple=True,clearable=True,with_input=True).classes('min-w-32')
    process_excel=ui.select(list(excel_task.keys()),clearable=True,with_input=True).classes('min-w-32')



def page():
    layout()